package com.maxd.modules.selfshop.prize.service.impl;

import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.UserInfo;
import com.maxd.modules.selfshop.prize.entity.SelfPrize;
import com.maxd.modules.selfshop.prize.entity.SelfPrizeUser;
import com.maxd.modules.selfshop.prize.service.SelfPrizeService;
import com.maxd.modules.selfshop.prize.service.SelfPrizeUserService;
import com.maxd.modules.selfshop.prize.entity.SelfPrizeRule;
import com.maxd.modules.selfshop.prize.respository.SelfPrizeJpaRepository;
import com.maxd.modules.selfshop.prize.respository.SelfPrizeRuleJpaRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SelfPrizeServiceImpl implements SelfPrizeService {
    @Autowired
    private SelfPrizeJpaRepository jpaRepository;
    @Autowired
    private SelfPrizeUserService selfPrizeUserService;
    @Autowired
    private SelfPrizeRuleJpaRepository selfPrizeRuleJpaRepository;
    @Autowired
    private UserJpaRepository userJpaRepository;

    @Override
    public Result findAll(Long prizeRuleId) {
        return ResultUtil.success(jpaRepository.findAllByPrizeRuleId(prizeRuleId));
    }

    @Override
    public Result saveBody(SelfPrize entity) {
        entity.setCreateTime(DateUtil.createTime());
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result updateBody(SelfPrize entity) {
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result findOne(Long id) {
        return ResultUtil.success(jpaRepository.findById(id).orElse(null));
    }

    @Override
    public Result delete(Long id) {
        jpaRepository.deleteById(id);
        return ResultUtil.success();
    }

    @Override
    public Result play(Long prizeRuleId, Long userId, String nickName) {
        //抽奖规则
        SelfPrizeRule selfPrizeRule = selfPrizeRuleJpaRepository.findById(prizeRuleId).orElse(null);
        //检测用户
        UserInfo user = userJpaRepository.findById(userId).orElse(null);
        if (user == null){
            return ResultUtil.error(-1, "用户不存在");
        }
        double userJiFen = Double.valueOf(user.getOrderJifen()).doubleValue();
        double needJiFen = Double.valueOf(selfPrizeRule.getJiFen()).doubleValue();
        if (userJiFen < needJiFen){ //检测用户积分
            return ResultUtil.error(-1, "积分不足");
        }
        //抽奖
        List<SelfPrize> list = jpaRepository.findAllByPrizeRuleId(prizeRuleId);
        int index = this.drawGame(list);
        SelfPrize p = list.get(index);
        //保存记录
        SelfPrizeUser u = new SelfPrizeUser();
        u.setUserId(userId);
        u.setNickName(nickName);
        u.setPrizeId(p.getPrizeId());
        u.setPrizeRuleId(p.getPrizeRuleId());
        u.setLessJiFen(selfPrizeRule.getJiFen());
        u.setAddJiFen(p.getAddJiFen().toString());
        selfPrizeUserService.saveBody(u);
        //返回中奖信息
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("index", index);
        map.put("prize", p);
        return ResultUtil.success(map);
    }

    /**
     * 计算概率
     */
    public int drawGame(List<SelfPrize> list){
        if(null != list && list.size()>0){
            List<Integer> orgProbList = new ArrayList<Integer>(list.size());
            for(SelfPrize p : list){
                //按顺序将概率添加到集合中
                orgProbList.add(p.getWeight());
            }
            return draw(orgProbList);
        }
        return -1;
    }
    public int draw(List<Integer> probList){
        List<Double> sortRateList = new ArrayList<Double>();
        // 计算概率总和
        Double sumRate = 0D;
        for(Integer prob : probList){
            sumRate += prob;
        }
        if(sumRate != 0){
            double rate = 0D;   //概率所占比例
            for(Integer prob : probList){
                rate += prob;
                // 构建一个比例区段组成的集合(避免概率和不为1)
                sortRateList.add(rate / sumRate);
            }
            // 随机生成一个随机数，并排序
            double random = Math.random();
            sortRateList.add(random);
            Collections.sort(sortRateList);
            // 返回该随机数在比例集合中的索引
            return sortRateList.indexOf(random);
        }
        return -1;
    }
}
